package com.tencent.cloud.iov.recycler.block;

import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import com.tencent.cloud.iov.action.IActionListener;
import com.tencent.cloud.iov.block.BlockManager;
import com.tencent.cloud.iov.block.IBlockLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 区块结构列表适配器
 *
 * @author showxiao
 * @date 2018/3/28
 */

public class BlockRecyclerAdapter<T> extends RecyclerView.Adapter<BlockViewHolder<T>> {

    /**
     * 区块布局行为响应视图
     */
    private IActionListener mActionListener;

    /**
     * 区块数据
     */
    private List<T> mItems;

    /**
     * 列表项类型集合：一种列表项类型对应一种区块布局
     */
    private List<Class<?>> mViewTypeList;

    public BlockRecyclerAdapter(IActionListener actionListener) {
        mActionListener = actionListener;
        mViewTypeList = new ArrayList<>();
    }

    public void swapData(List<T> items) {
        List<T> oldItems = mItems;

        mItems = new ArrayList<>();
        if (items != null && !items.isEmpty()) {
            mItems.addAll(items);
        }

        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(
                new DiffCallback<>(oldItems, mItems), true);
        diffResult.dispatchUpdatesTo(this);
    }

    @Override
    public int getItemViewType(int position) {
        Class<?> clazz = mItems.get(position).getClass();
        if (!mViewTypeList.contains(clazz)) {
            mViewTypeList.add(clazz);
        }

        return mViewTypeList.indexOf(clazz);
    }

    @Override
    @SuppressWarnings("unchecked")
    public BlockViewHolder<T> onCreateViewHolder(ViewGroup parent, int viewType) {
        Class<?> itemClass = mViewTypeList.get(viewType);
        IBlockLayout blockLayout = BlockManager.createBlockLayout(itemClass);
        return (BlockViewHolder) new BlockViewHolder<>(blockLayout, parent);
    }

    @Override
    public void onBindViewHolder(BlockViewHolder<T> holder, int position) {
        holder.onBindView(mItems.get(position), position, mActionListener);
    }

    @Override
    public int getItemCount() {
        return mItems != null ? mItems.size() : 0;
    }

    public T getItem(int position) {
        return mItems != null && mItems.size() > position ? mItems.get(position) : null;
    }
}
